package com.tarena.lbs.business.servcie.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.attach.pojo.param.PicUpdateParam;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.model.Result;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.dao.repository.BusinessRepository;
import com.tarena.lbs.business.dao.repository.StoreRepository;
import com.tarena.lbs.business.pojo.param.BusinessParam;
import com.tarena.lbs.business.pojo.param.StoreParam;
import com.tarena.lbs.business.pojo.po.BusinessPO;
import com.tarena.lbs.business.pojo.query.BusinessQuery;
import com.tarena.lbs.business.pojo.query.StoreQuery;
import com.tarena.lbs.business.pojo.vo.BusinessStoreVO;
import com.tarena.lbs.business.pojo.vo.BusinessVO;
import com.tarena.lbs.business.servcie.BusinessService;
import com.tarena.lbs.business.servcie.StoreService;
import com.tarena.lbs.common.enums.BusinessTypeEnum;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.user.api.UserApi;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class BusinessServiceImpl implements BusinessService {
    @Autowired
    private BusinessRepository businessRepository;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private AttachApi attachApi;

    @Autowired
    private StoreService storeService;

    @Override
    public PageResult<BusinessVO> pageList(BusinessQuery query) throws BusinessException {
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        if (userPrinciple  != null) {
            if (userPrinciple.getRole() == Roles.ADMIN) {
                // 创建一个新的分页结果对象，用于存储最终的分页查询结果
                PageResult<BusinessVO> voPage = new PageResult<>();
                //total objects pageNo pageSize totalPage
                // 调用 businessRepository 的 pagesList 方法进行分页查询，获取包含商家持久化对象的分页信息
                PageInfo<BusinessPO> pageInfo = businessRepository.pagesList(query);
                //pageNo pageSize total
                // 将分页信息中的页码设置到分页结果对象中
                voPage.setPageNo(pageInfo.getPageNum());
                // 将分页信息中的每页数量设置到分页结果对象中
                voPage.setPageSize(pageInfo.getPageSize());
                // 将分页信息中的总记录数设置到分页结果对象中
                voPage.setTotal(pageInfo.getTotal());
                // 声明一个存储管理员视图对象的列表
                List<BusinessVO> vos = null;
                // 从分页信息中获取商家持久化对象列表
                List<BusinessPO> pos = pageInfo.getList();
                // 判断持久化对象列表是否不为空
                if (CollectionUtils.isNotEmpty(pos)) {
                    vos = pos.stream().map(po -> {
                        BusinessVO vo = new BusinessVO();
                        org.springframework.beans.BeanUtils.copyProperties(po, vo);
                        return vo;
                    }).collect(Collectors.toList());
                }
                voPage.setObjects(vos);
                return voPage;
            } else if (userPrinciple.getRole() == Roles.SHOP) {
                AdminDto adminDto = userApi.getAdminById(userPrinciple.getId());
                query.setBusinessId(adminDto.getBusinessId());
                // 创建一个新的分页结果对象，用于存储最终的分页查询结果
                PageResult<BusinessVO> voPage = new PageResult<>();
                //total objects pageNo pageSize totalPage
                // 调用 businessRepository 的 pagesList 方法进行分页查询，获取包含商家持久化对象的分页信息
                PageInfo<BusinessPO> pageInfo = businessRepository.pagesList(query);
                //pageNo pageSize total
                // 将分页信息中的页码设置到分页结果对象中
                voPage.setPageNo(pageInfo.getPageNum());
                // 将分页信息中的每页数量设置到分页结果对象中
                voPage.setPageSize(pageInfo.getPageSize());
                // 将分页信息中的总记录数设置到分页结果对象中
                voPage.setTotal(pageInfo.getTotal());
                // 声明一个存储管理员视图对象的列表
                List<BusinessVO> vos = null;
                // 从分页信息中获取商家持久化对象列表
                List<BusinessPO> pos = pageInfo.getList();
                // 判断持久化对象列表是否不为空
                if (CollectionUtils.isNotEmpty(pos)) {
                    vos = pos.stream().map(po -> {
                        BusinessVO vo = new BusinessVO();
                        org.springframework.beans.BeanUtils.copyProperties(po, vo);
                        return vo;
                    }).collect(Collectors.toList());
                }
                voPage.setObjects(vos);
                return voPage;
            } else {
                throw new BusinessException("-2", "认证失败");
            }
        }else {
            throw new BusinessException("-1", "请先登录");
        }
    }

    @Override
    public BusinessStoreVO busiStoreDetail(Integer businessId) throws BusinessException {
        BusinessStoreVO vo = new BusinessStoreVO();
        BusinessPO po = businessRepository.getById(businessId);
        StoreQuery query = new StoreQuery();
        query.setBusinessId(businessId);
        vo.setStoreVOList(storeService.pageList(query).getObjects());
        BeanUtils.copyProperties(po, vo);
        return vo;
    }

    @Override
    public void save(BusinessParam param) throws BusinessException {
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        if (userPrinciple  != null) {
            if (userPrinciple.getRole() == Roles.ADMIN) {
                BusinessPO po = new BusinessPO();
                BeanUtils.copyProperties(param, po);
                po.setEntryTime(new Date());
                po.setBusinessStatus(1);
                po.setAuditRemarks("待审核");
                //判断商家名称是否重复
                BusinessPO po1 = businessRepository.getById(param.getId());
                //通过po1的id查询商家列表拿到商家名称
                if (po1 != null && po1.getBusinessName().equals(po.getBusinessName())) {
                    throw new BusinessException("-3", "商家名称重复");
                }else{
                    businessRepository.save(po);
                }
                businessRepository.getById(param.getId());
                //通过调用attachApi的batchUpdateBusiness方法批量更新商家图片
                //封装商家营业执照
                /*List<PicUpdateParam> picParams = new ArrayList<>();
                String businessLicense = param.getBusinessLicense();
                PicUpdateParam picParam = new PicUpdateParam();
                picParam.setId(Integer.parseInt(businessLicense));
                picParam.setBusinessType(BusinessTypeEnum.BUSINESS_LICENSE.getType());
                picParam.setBusinessId(po.getId());
                log.debug("封装信息picParam:{}",picParam);
                picParams.add(picParam);
                attachApi.batchUpdateBusiness(picParams);

                //封装商家Logo
                List<PicUpdateParam> picParams22 = new ArrayList<>();
                String businessLogo = param.getBusinessLogo();
                PicUpdateParam picParam22 = new PicUpdateParam();
                picParam22.setId(Integer.parseInt(businessLogo));
                picParam22.setBusinessType(BusinessTypeEnum.BUSINESS_LOGO.getType());
                picParam22.setBusinessId(po.getId());
                log.debug("封装信息picParam22:{}",picParam22);
                picParams22.add(picParam22);
                attachApi.batchUpdateBusiness(picParams22);*/
            }else {
                throw new BusinessException("-2", "认证失败");
            }
        }else {
            throw new BusinessException("-1", "请先登录");
        }
    }

    @Override
    public void updateStatus(BusinessParam param) throws BusinessException {
        BusinessPO po = businessRepository.getById(param.getId());
        if (po == null) {
            throw new BusinessException("-4", "商家不存在");
        }
        po.setBusinessStatus(param.getBusinessStatus());
        po.setAuditRemarks(param.getAuditRemarks());
        businessRepository.updateById(po);
    }
}
